package com.jzo2o.market.handler;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.jzo2o.market.enums.ActivityStatusEnum;
import com.jzo2o.market.model.domain.Activity;
import com.jzo2o.market.service.IActivityService;
import com.jzo2o.market.service.ICouponService;
import com.jzo2o.redis.annotations.Lock;
import com.jzo2o.redis.constants.RedisSyncQueueConstants;
import com.jzo2o.redis.sync.SyncManager;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import java.time.LocalDateTime;

import static com.jzo2o.market.constants.RedisConstants.Formatter.*;
import static com.jzo2o.market.constants.RedisConstants.RedisKey.COUPON_SEIZE_SYNC_QUEUE_NAME;

@Component
public class XxlJobHandler {

    @Resource
    private SyncManager syncManager;

    @Resource
    private IActivityService activityService;

    @Resource
    private ICouponService couponService;

    @Resource
    private IssuedCouponHandlerJob issuedCouponHandlerJob;
    /**
     * 活动状态修改，
     * 1.活动进行中状态修改
     * 2.活动已失效状态修改
     * 1分钟一次
     */
    @XxlJob("updateActivityStatus")
    public void updateActivitySatus(){
        LambdaUpdateWrapper<Activity> objectLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        LambdaUpdateWrapper<Activity> query = objectLambdaUpdateWrapper.eq(Activity::getStatus, ActivityStatusEnum.NO_DISTRIBUTE.getStatus())
                .gt(Activity::getDistributeStartTime, LocalDateTime.now())
                .lt(Activity::getDistributeStartTime, LocalDateTime.now())
                .set(Activity::getStatus, ActivityStatusEnum.DISTRIBUTING.getStatus());
        activityService.update(query);

        query=objectLambdaUpdateWrapper.eq(Activity::getStatus, ActivityStatusEnum.DISTRIBUTING.getStatus())
                .lt(Activity::getDistributeEndTime, LocalDateTime.now())
                .set(Activity::getStatus, ActivityStatusEnum.LOSE_EFFICACY.getStatus());
        activityService.update(query);
    }

    /**
     * 已领取优惠券自动过期任务
     */
    @XxlJob("processExpireCoupon")
    public void processExpireCoupon() {

        couponService.useExprieCoupon();
    }
    @XxlJob("issueCouponJob")
    public void issueCouponJob() {
        issuedCouponHandlerJob.start();
    }


}
